package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.*;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private EmpExprMapper empExprMapper;

    @Autowired
    private EmpLogService empLogService;

    /**
     * 分页查询
     * @param page     页码  1、2、3
     * @param pageSize 每页记录数 5、10
     * @return
     */
    // @Override
    // public PageBean page(Integer page, Integer pageSize) {
    //     //1.调用mapper获取总记录数  total
    //     // select count(*) from emp;
    //     Long total = empMapper.count();
    //
    //     //2.调用mapper获取分页列表数据 rows
    //     //select e.name, e.gender,e.image,d.name,e.job from emp e left join dept d on e.dept_id = d.id limit 0, 5;
    //     Integer start = (page - 1) * pageSize;  //计算起始索引
    //     List<Emp> empList = empMapper.page(start, pageSize);
    //
    //     //3.封装PageBean对象并返回
    //     return new PageBean(total, empList);
    // }

    // @Override
    // public PageBean page(Integer page, Integer pageSize) {
    //     //1.设置分页参数
    //     PageHelper.startPage(page, pageSize);
    //
    //     //2.调用mapper的列表查询方法
    //     List<Emp> empList = empMapper.list();
    //     Page p = (Page) empList;        //强转对象，Page继承了ArrayList
    //
    //     //分页只会对PageHelper.startPage()下面的第一条select进行处理
    //     // List<Emp> empList2 = empMapper.list();
    //
    //     //3.封装PageBean对象并返回
    //     return new PageBean(p.getTotal(), p.getResult());
    //     // return new PageBean(p.getTotal(), p);
    //     // return new PageBean(p.getTotal(), empList);
    // }

    @Override
    public PageBean page(EmpQueryParam param) {
        //1.设置分页参数
        PageHelper.startPage(param.getPage(), param.getPageSize());

        //2.调用mapper的列表查询方法
        List<Emp> empList = empMapper.list(param);
        Page p = (Page) empList;        //强转对象，Page继承了ArrayList

        //3.封装PageBean对象并返回
        return new PageBean(p.getTotal(), p.getResult());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(Emp emp) {
        try {
            //1. 调用mapper方法，保存员工的基本信息到emp表；
            emp.setPassword("123456");
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            empMapper.insert(emp);

            Integer id = emp.getId();
            log.info("id={}", id);

            //2.调用mapper方法，保存员工工作经历到expr表
            List<EmpExpr> exprList = emp.getExprList();

            if (!CollectionUtils.isEmpty(exprList)) {
                exprList.forEach((expr) -> {
                    expr.setEmpId(id);
                });
                empExprMapper.insertBatch(exprList);

            }
        }finally {
            EmpLog empLog = new EmpLog();
            empLog.setOperateTime(LocalDateTime.now());
            empLog.setInfo("插入员工信息" + emp);
            empLogService.insertEmpLog(empLog);
        }
    }
    @Transactional
    public void delete(List<Integer> ids){
        empMapper.deleteBatch(ids);

        empExprMapper.deleteBatch(ids);
    }

    @Override
    public Emp getById(Integer id){
//        Emp emp = empMapper.getById(id);

//        方式二
        Emp emp = empMapper.getById2(id);

        List<EmpExpr> empExprList = empExprMapper.getByEmpId(id);
        emp.setExprList(empExprList);

        return emp;
    }

    @Override
    @Transactional
    public void update(Emp emp){
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);
        List<Integer> empIdList = new ArrayList<>();
        empIdList.add(emp.getId());
        empExprMapper.deleteBatch(empIdList);

        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)) {
            exprList.forEach((expr)->{
                expr.setEmpId(emp.getId());
            });

            empExprMapper.insertBatch(exprList);
        }
    }

    @Override
    public EmpLoginInfo login(Emp emp) {
        Emp empDB = empMapper.selectUNandP(emp);

        if(empDB != null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", empDB.getId());
            claims.put("username", empDB.getUsername());
            String jwt = JwtUtils.generateJwt(claims);
            return new EmpLoginInfo(empDB.getId(), empDB.getUsername(), empDB.getPassword(), jwt);
        }

        return null;
    }

}
